const app = getApp();
Page({
  data: {
    goods:[],
    couponIndex: 0,
    invoices: '',
  },
  onLoad: function (options) {
    let that = this;
    let city_id = wx.getStorageSync('city_id');
    let shopcar = options.shopcar ? JSON.parse(options.shopcar) : '';
    let goodsInfo = options.data ? encodeURIComponent(options.data) :'';
    wx.showLoading({
      title: '加载中...',
    })
    that.setData({
      shopcar, goodsInfo
    })
    if (shopcar){
      app.request('order/placeOrder', { city_id, shopcar }, 'POST', false, function (res) {
        that.getInfo(res);
      })
    }else{
      app.request('order/placeOrder', { city_id, goodsInfo }, 'POST', false, function (res) {
        that.getInfo(res);
      })
    }
    
  },
  getInfo(res){
    let that = this;
    res.data.data.coupon.length>0 ? res.data.data.coupon.unshift({ id: '0', name: '不使用优惠券' }) : '';
    res.data.data.paytype.map((v, k) => {
      v.checked = false;
    })
    let goods_num = 0;
    if (res.data.data.goods.list.goods) {
      res.data.data.goods.list.goods.map((v, k) => {
        goods_num += v.total_num;
        v.specType = 0;
      })
    }
    if (res.data.data.goods.list.package) {
      for (let i in res.data.data.goods.list.package) {
        let total_num = 0;
        let goods_price = 0;
        res.data.data.goods.list.package[i].goods.map((v, k) => {
          goods_num += v.total_num;
          total_num += v.total_num;

          goods_price = (parseFloat(v.goods_price * v.total_num) + parseFloat(goods_price)).toFixed(2);
        })
        res.data.data.goods.list.package[i]['specType'] = 1;
        res.data.data.goods.list.package[i]['total_num'] = total_num;
        res.data.data.goods.list.package[i]['goods_price'] = goods_price;
      }
    }
    let total_price = (parseFloat(res.data.data.goods.money) + parseFloat(res.data.data.postage.now_postage)).toFixed(2);
    that.setData({
      pageShow: true,
      file: res.data.data.file,
      address: res.data.data.address,
      postage: res.data.data.postage,
      coupon: res.data.data.coupon,
      phone: res.data.data.phone,
      paytype: res.data.data.paytype,
      goods: res.data.data.goods.list,
      money: res.data.data.goods.money,
      total_price: total_price,
      goods_num: goods_num,
    })
  },
  onShow: function () {
    let that = this;
    if (wx.getStorageSync('addressChoose')){
      that.setData({
        address: wx.getStorageSync('addressChoose'),
      },()=>{
        wx.removeStorageSync('addressChoose');
      })
    }
    if (wx.getStorageSync('invoiceChoose')) {
      that.setData({
        invoices: wx.getStorageSync('invoiceChoose'),
      }, () => {
        wx.removeStorageSync('invoiceChoose');
      })
    }
  },
  skipPage(e){
    app.skipPage(e);
  },
  maskPhoneCall(e){
    let that = this;
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },
  couponChange: function (e) {
    let that = this;
    let couponIndex = e.detail.value;
    let coupon = that.data.coupon;
    let count_price = new Number();
    if (coupon[couponIndex].coupon_type.value == 1 && couponIndex!=0){
      count_price = (parseFloat(that.data.total_price) - parseFloat(coupon[couponIndex].reduce_price)).toFixed(2);
    }else{
      count_price = ((parseFloat(that.data.money) * parseFloat(coupon[couponIndex].discount) / 100) + parseFloat(that.data.postage.now_postage)).toFixed(2);
    }
    that.setData({
      count_price: count_price,
      couponIndex: couponIndex
    })
  },
  getInput(e){
    let that = this;
    console.log(e)
    that.setData({
      buyer_remark: e.detail.value,
    })
  },
  payChange:function(e){
    let that = this;
    that.setData({
      payIndex: e.detail.value
    })
  },
  previewFile(e){
    let that = this;
    let filePath = that.data.list[index].path;
    wx.downloadFile({
      url: filePath,
      success(res) {
        wx.openDocument({
          filePath: res.tempFilePath,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail(res) {
            wx.showToast({
              title: '文档格式不支持',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  sure(){
    let that = this;
    let address_id = that.data.address.id || '';
    if(!address_id){
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
      })
      return false;
    }
    let pay_type = that.data.payIndex || '';
    if (!pay_type) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
      })
      return false;
    }
    let shopcar = that.data.shopcar;
    let goodsInfo = that.data.goodsInfo;
    let city_id = wx.getStorageSync('city_id');
    let coupon_id = that.data.couponIndex != 0 ? that.data.coupon[that.data.couponIndex].id : '';
    let invoices_id = that.data.invoices.id || '';
    let buyer_remark = that.data.buyer_remark || '';
    wx.showLoading({
      title: '生成订单...',
      icon: 'loading',
      mask: true,
    })
    if (shopcar) {
      app.request('order/saveOrder', {
        shopcar, city_id, address_id, coupon_id, invoices_id, pay_type, buyer_remark
      }, 'POST',false,function(res){
        that.placeOrder(res);
      })
    }else{
      app.request('order/saveOrder', {
        goodsInfo, city_id, address_id, coupon_id, invoices_id, pay_type, buyer_remark
      }, 'POST', false, function (res) {
        that.placeOrder(res);
      })
    }
  },
  placeOrder(res){
    let that = this;
    if(that.data.payIndex == 1){
      let order_id = res.data.data.order_id;
      wx.hideLoading();
      app.request('pay/payOrder',{ order_id },'GET',false,function(res){
        wx.requestPayment({
          'timeStamp': res.data.data.timeStamp,
          'nonceStr': res.data.data.nonceStr,
          'package': res.data.data.package,
          'signType': res.data.data.signType,
          'paySign': res.data.data.paySign,
          success: function (res) {
            wx.showToast({
              title: '支付成功',
              mask: true,
            });
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/mine/mine',
              })
            }, 2000)
          },
          complete(res){
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }
        });
      })
    }else{
      wx.switchTab({
        url: '/pages/mine/mine',
      })
    }
    
  },
})